package com.app.micaihu.view.main.topic.fragment;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.android.volley.VolleyError;
import com.app.config.LoadViewConfig;
import com.app.micaihu.R;
import com.app.micaihu.app.AppApplication;
import com.app.micaihu.base.BaseListFragment;
import com.app.micaihu.base.bean.DataBean;
import com.app.micaihu.bean.news.NewsEntity;
import com.app.micaihu.bean.topic.PostItemBean;
import com.app.micaihu.bean.topic.RecommendTopicList;
import com.app.micaihu.bean.topic.TopicInfo;
import com.app.micaihu.configure.Config;
import com.app.micaihu.configure.ConfigKeyConstant;
import com.app.micaihu.configure.TypeConstant;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.configure.UmEventId;
import com.app.micaihu.listener.HttpListener;
import com.app.micaihu.manager.AppConfigManager;
import com.app.micaihu.manager.UserInforManager;
import com.app.micaihu.utils.DialogUtils;
import com.app.micaihu.utils.MobclickAgentUtils;
import com.app.micaihu.utils.StatServiceUtils;
import com.app.micaihu.videoplayer.JCMediaManager;
import com.app.micaihu.videoplayer.JCVideoPlayer;
import com.app.micaihu.view.main.topic.PostSendActivity;
import com.app.micaihu.view.main.topic.adapter.PostItemAdapter;
import com.app.utils.pulltorefresh.PullToRefreshBase;
import com.app.utils.util.StringUtils;
import com.baidu.mobstat.StatService;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * 帖子Fragment
 * Created by linkai on 2016/7/14.
 */
public class TopicRecommendFragment extends BaseListFragment<PostItemBean> {

    /*********
     * 逻辑数据
     **********/
    private String indexType;//排序规则 1最新 2最热
    private int mMark;//下拉刷新请求标识
    int mFlushIndex = -1;//刷新下标
    private boolean isinit;//是否初始化（用于下拉刷新数据）

    private String lastGetTime = "";

    //已经加载过的新闻 （用于新闻去重）
    private HashMap<String, String> listHasp = new HashMap<String, String>();

    //操作监听
    private OnRefreshingListener mOnRefreshingListener;
    private View confirmDialog;
    private HashMap<String, Object> dialogParams;
    private int refreshTime;//初次初始化的时间
    private int onResumeTime;//获取焦点的时间
    private int onPauseTime;//失去焦点的时间
    private int topicExpireTimeInt;//前页面 的刷新间隔事件

    private boolean isStop;//listView是否停止
    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (msg.what == 1) {
                int onClickTime = (int) (System.currentTimeMillis() / 1000);
                if (refreshTime > 0
                        && ((onClickTime - refreshTime) > topicExpireTimeInt)) {
                    flushData(true);
                }
            }

        }
    };

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        indexType = (args != null ? args.getString("indexType", "1") : "1");
        EventBus.getDefault().register(this);

        String topicExpireTime = AppConfigManager.getInstance().readConfig(ConfigKeyConstant.topicExpireTime, "3600");
        topicExpireTimeInt = StringUtils.toInt(topicExpireTime, 3600);

    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ivTopic.setVisibility(View.VISIBLE);
        ivTopic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                StatServiceUtils.event(Config.EventBauduId.square_post, "广场_发帖");

                Intent intent = new Intent(activity, PostSendActivity.class);
                startActivity(intent);
                activity.overridePendingTransition(R.anim.translate_slide_in_bottom, R.anim.slide_out_left);
            }
        });


        mListView.getRefreshableView().setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                isScroll = true;
                return false;
            }
        });

        mListView.getRefreshableView().setOnScrollListener(new AbsListView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    if (isStop && !mListView.isRefreshing()) {
                        mListView.showFootView();
                        onPullUpToRefresh(mListView);
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if ((totalItemCount > 0) && (firstVisibleItem + visibleItemCount >= totalItemCount - 1)) {
                    isStop = true;
                } else {
                    isStop = false;
                }
                //滚动过程中：ListView中最上面一个Item还是同一个Item
                if (isScroll) {
                    if (isSameRow(firstVisibleItem)) {
                        int newScrollY = getTopItemScrollY();
                        boolean isExceedThreshold = Math.abs(mLastScrollY - newScrollY) > mScrollThreshold;
                        if (isExceedThreshold) {
                            if (mLastScrollY > newScrollY && FAB_VISIBLE == true) {
                                FAB_VISIBLE = false;
                                hideFAB();
                            } else if (mLastScrollY < newScrollY && FAB_VISIBLE == false) {
                                FAB_VISIBLE = true;
                                showFAB();
                            }
                        }
                        mLastScrollY = newScrollY;
                    } else {
                        if (firstVisibleItem > mPreviousFirstVisibleItem && FAB_VISIBLE == true) {  //向下滚动
                            FAB_VISIBLE = false;
                            hideFAB();
                        } else if (firstVisibleItem < mPreviousFirstVisibleItem && FAB_VISIBLE == false) { //向上滚动
                            FAB_VISIBLE = true;
                            showFAB();
                        }
                        mLastScrollY = getTopItemScrollY();
                        mPreviousFirstVisibleItem = firstVisibleItem;
                    }

                }
            }
        });

    }
    private boolean isScroll = false;
    private boolean FAB_VISIBLE = true;
    private int mPreviousFirstVisibleItem;   //记录前面第一个Item
    private int mLastScrollY;            //记录ListView中最上面的Item(View)的上一次顶部Y坐标()
    private int mScrollThreshold = 2;   //阈值：单位px

    private boolean isSameRow(int firstVisisbleItem) {
        return mPreviousFirstVisibleItem == firstVisisbleItem;
    }

    /**
     * 滚动过程中，获得当前ListView中最上面的Item(View)的顶部的Y坐标(以px为单位)
     *
     * @return
     */
    private int getTopItemScrollY() {
        if (mListView == null || mListView.getChildAt(0) == null) return 0;
        View topChild = mListView.getChildAt(0);
        return topChild.getTop();
    }

    private boolean isAnimatorEnd;

    private void hideFAB() {
        isAnimatorEnd = false;
        ObjectAnimator animator = ObjectAnimator.ofFloat(ivTopic, "translationX", SizeUtils.dp2px(70f));
        animator.setDuration(600);
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                isAnimatorEnd = true;
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        animator.start();


    }

    private void showFAB() {
        ObjectAnimator animator = ObjectAnimator.ofFloat(ivTopic, "translationX", 0);
        animator.setDuration(600);
        if (!isAnimatorEnd) {
            animator.setStartDelay(1200);
        }
        animator.start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //销毁 eventbus
        EventBus.getDefault().unregister(this);
    }

    /**
     * 别的界面操作主界面的事件
     *
     * @param bundle
     */
    public void onEventMainThread(Bundle bundle) {
        if (bundle == null) return;
        int type = bundle.getInt("type");
        switch (type) {
            case 1://关注
                String status = bundle.getString(Config.Extra.PARAMETER1);
                String uid = bundle.getString(Config.Extra.PARAMETER2);
                if (dataList != null) {
                    for (int i = 0; i < dataList.size(); i++) {
                        if (TextUtils.equals(dataList.get(i).getUid(), uid)) {
                            dataList.get(i).setIAttType(status);
                        }
                    }
                }
                if (mAdapter != null) {
                    mAdapter.notifyDataSetChanged();
                }
                break;
            case 2://发帖回来
                if (TextUtils.equals("1", indexType)) {
                    PostItemBean post = (PostItemBean) bundle.getSerializable("post");
                    boolean postTitle = bundle.getBoolean("postTitle", false);
                    if (post != null) {
                        post.setCtype(TypeConstant.NORMAL_POST);
                        if (bundle.getSerializable("post") != null) {
                            addPostData(post);
                        }
                        showConfirmDialog(postTitle);
                    }
                }
                break;


            case 3://刷新当前 评论和点赞

                try {
                    boolean delete = bundle.getBoolean("delete", false);
                    String zan = bundle.getString("zan");
                    String comment = bundle.getString("comment");
                    updateAdapter(StringUtils.toInt(zan, 0), StringUtils.toInt(comment, 0), delete);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;

            case 4://当mainActivity 中点击事件被触发,判断间隔刷新
                int onClickTime = (int) (System.currentTimeMillis() / 1000);
//                LogUtils.e("gzq", "tiem = "+time);
//                LogUtils.e("gzq", "onThreadMain = "+"refreshTime = "+refreshTime + "   onClickTime = "+onClickTime + "  差值 =  "+(onClickTime - refreshTime));
                if (refreshTime > 0
                        && ((onClickTime - refreshTime) > topicExpireTimeInt)) {
                    if (mListView != null) {
                        try {

                            mListView.getRefreshableView().setSelection(0);

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                    flushData(true);

                }


                break;
        }
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view.getId() == R.id.empty_page) {
            changeData(true);
        }
        if (view.getId() == R.id.tv_ok) {
            DialogUtils.getInstance().dismissCDialog();
        }
    }

    /**
     * 发帖成功后 添加数据
     *
     * @param postItemBean
     */
    public void addPostData(PostItemBean postItemBean) {
        if (postItemBean == null) {
            return;
        }
        if (dataList == null) {
            dataList = new ArrayList<PostItemBean>();
        }

        if (dataList.isEmpty()) {
            setLoadView(LOADSUCES, "");
        }

        dataList.add(0, postItemBean);
        listHasp.put(postItemBean.getICommentId(), postItemBean.getICommentId());
        if (mAdapter == null) {
            mAdapter = new PostItemAdapter(dataList, getActivity(), true, indexType);
            if (mListView != null) {
                mListView.setAdapter(mAdapter);
            }
        } else {
            mAdapter.notifyDataSetChanged();
        }


    }

    /**
     * 发帖成功 的弹窗
     *
     * @param postTitle
     */
    private void showConfirmDialog(final boolean postTitle) {
        if (mListView == null) return;
        mListView.postDelayed(new Runnable() {
            @Override
            public void run() {
                Activity lastActivity = ActivityUtils.getTopActivity();
                if (lastActivity != null && !lastActivity.isFinishing()) {
                    View confirmDialog = LayoutInflater.from(lastActivity).inflate(R.layout.dialog_send_post, null);
                    TextView title = (TextView) confirmDialog.findViewById(R.id.tv_title);
                    if (postTitle) {
                        title.setText(AppApplication.getInstance().getString(R.string.send_post_shaidan_ok));
                    } else {
                        title.setText(AppApplication.getInstance().getString(R.string.send_post_ok));
                    }
                    TextView confirm = (TextView) confirmDialog.findViewById(R.id.tv_ok);
                    confirm.setOnClickListener(TopicRecommendFragment.this);
                    if (dialogParams == null) {
                        dialogParams = new HashMap<>();
                        dialogParams.put("local", Gravity.CENTER);
                        dialogParams.put("width", 280);
                    }
                    DialogUtils.getInstance().showCDialog(confirmDialog, lastActivity, dialogParams);
                }
            }
        }, 300);


    }


    @Override
    public void onResume() {
        super.onResume();

        //获取 获得焦点的 时间,以秒做单位
        onResumeTime = (int) (System.currentTimeMillis() / 1000);
        //判断.如果间隔 大于服务器时间,
//        LogUtils.e("gzq", "onR " +"onPauseTime = "+onPauseTime + "  onResume = "+onResumeTime+"  差值 = "+(onResumeTime - onPauseTime) + " 间隔 =  "+topicExpireTimeInt);
        if (onPauseTime > 0 && onResumeTime - onPauseTime > topicExpireTimeInt
                && dataList != null && !dataList.isEmpty()) {
            if (mListView != null) {
                mListView.getRefreshableView().setSelection(0);
            }
            flushData(true);
        }

    }


    @Override
    public void onPause() {
        super.onPause();
        //记录失去焦点 的时间,以秒做单位
        onPauseTime = (int) (System.currentTimeMillis() / 1000);
//        LogUtils.e("gzq", "onPauseTime = = = = "+onPauseTime);
    }

    @Override
    protected void changeData(final boolean isRefresh) {
        HashMap<String, String> parmsMap = new HashMap<String, String>();
        parmsMap.put("type", indexType + "");
        parmsMap.put("page", dataPage + "");
        parmsMap.put("mark", mMark + "");
        parmsMap.put("lastGetTime", lastGetTime + "");
        if (UserInforManager.getInstance().isLogin()) {
            parmsMap.put("uid", UserInforManager.getInstance().getUserInfor().getUid());
        }
        HttpListener<DataBean<RecommendTopicList>> httpListener = new HttpListener<DataBean<RecommendTopicList>>() {

            @Override
            public void onStart() {
                setLoadView(LOADING, null);
                //改变导航栏底部图标
                if (isRefresh && mMark == 1) {
                    if (mOnRefreshingListener != null) {
                        mOnRefreshingListener.onDataRefreshingStart();
                    }
                }
            }

            @Override
            public void onError(VolleyError error) {
                if (mOnRefreshingListener != null) {
                    mOnRefreshingListener.onDataRefreshingEnd();
                }
                setLoadView(NO_NET, AppApplication.getInstance().getString(R.string.neterror));
            }

            @Override
            public void onSuccess(DataBean<RecommendTopicList> response) {

                if (response != null && response.noError()) {
                    //拿取 当次 获取到的 列表
                    RecommendTopicList newsList = response.getData();

                    //如果当前获取到的数据不为空
                    if (newsList != null) {
                        //拿取 列表数据
                        List<PostItemBean> list = newsList.getCmtList();
                        //列表数据不为空,且有多余一个元素
                        if (list != null && list.size() > 0) {
                            //当前所有列表 如果为null,new 一个
                            if (dataList == null) {
                                dataList = new ArrayList<PostItemBean>();
                            }
                            //使用hashmap 去重,以commentId 为key,value
                            dataRevisited(list);
                            //如果是下拉操作
                            if (isRefresh) {
                                //为time 赋值
                                lastGetTime = newsList.getLastGetTime();

                                refreshTime = (int) (System.currentTimeMillis() / 1000);
                                //如果是初始化 的刷新操作
                                if (mMark == 0) {
                                    //如果mark为0 说明是初始化的刷新
//                                    initHeadData(newsList.getTopicInfo());//刷新头部轮播
                                    //清空 当前列表
                                    dataList.clear();
                                    //将服务器的数据填充到 当前列表
                                    dataList.addAll(list);

                                    //设置tag.表示下次 不是初始化
                                    isinit = false;//下次则不再初始化下拉数据
                                } else {
                                    //不是初始化操作.当前列表已经有数据了.拿取随机数据
                                    //如果已经有刷新item,并且刷新item的index < 当前总数据的 size();则将它移除
                                    if (mFlushIndex >= 0 && mFlushIndex < dataList.size()) {
                                        dataList.remove(mFlushIndex);
                                    }
//                                    initHeadData(newsList.getTopicInfo());//刷新头部轮播
                                    //new 一个刷新item
                                    PostItemBean newsFlush = new PostItemBean();
                                    newsFlush.setCtype(TypeConstant.FLUSH + "");

                                    //将这个刷新item 放到 当前获取到的数据的最尾
                                    list.add(newsFlush);

                                    //如果当前是有数据的
                                    if (list.size() > 1) {
                                        //最后一个位置添加刷新数据
                                        //1,2,3,4,flash
                                        //5-1 = 4
                                        mFlushIndex = list.size() - 1;
                                        try {
//                                            int index = topIndex + 1 > dataList.size() ? dataList.size() : topIndex + 1;
                                            dataList.addAll(0, list);
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }

                                    }
                                }
                            } else {
                                //追加数据集合
                                dataList.addAll(list);
                            }
                            if (mAdapter == null) {
                                mAdapter = new PostItemAdapter(dataList, activity, false, indexType);
                                mListView.setAdapter(mAdapter);
                            } else {
                                mAdapter.notifyDataSetChanged();
                            }
                            if (isRefresh) {

                                if (list.size() > 1) {
                                    if (mMark != 0) {
                                        String msg;
                                        msg = "推荐引擎有<font color='#5a9722'>" + (list.size() - 1) + "</font>条新数据";
                                        setLoadView(LOADSUCES, Html.fromHtml(msg));
                                    } else {
                                        setLoadView(LOADSUCES, "");
                                    }
                                } else {
                                    //updateLoadView(LOADSUCES, "暂无新数据");
                                    setLoadView(LOADSUCES, "");
                                }

                            } else {
                                setLoadView(LOADSUCES, "");
                            }
                        } else {
                            if (dataList == null || dataList.size() == 0) {
                                setLoadView(DATAEMPTY, "");
                            } else {
                                setLoadView(LOADSUCES, getString(R.string.pullup_nomore_data));
                            }
                        }

                    } else {
                        setLoadView(DATAERROR, response.getErrorMsg());
                    }
                } else {
                    setLoadView(DATAERROR, response.getMsg());
                }
            }
        };
        if (mMark >= 1) {
            //下拉刷新无缓存
            addPostRequest(URIContant.POST_LIST, new TypeToken<DataBean<RecommendTopicList>>() {
            }.getType(), parmsMap, httpListener);
        } else {
            //加载更多有缓存
            addPostCacheRequest(URIContant.POST_LIST, new TypeToken<DataBean<RecommendTopicList>>() {
            }.getType(), parmsMap, httpListener);
        }
    }

    /**
     * LoadViewd 方法
     *
     * @param code 传入对应的值
     * @param msg  提示的的文字
     */
    protected void setLoadView(int code, CharSequence msg) {

        switch (code) {
            case NO_NET://网络错误
            case DATAERROR://数据错误
                if (dataList == null || dataList.size() == 0) {
                    mLoadView.showErrorPage(msg);
                }
                if (mListView != null) {
                    mListView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mListView.onRefreshComplete();
                            //更改 底部导航栏
                            if (mOnRefreshingListener != null) {
                                mOnRefreshingListener.onDataRefreshingEnd();
                            }
                        }
                    }, 800);
                }
                break;
            case LOADING://加载中
                if (dataList == null || dataList.size() == 0) {
                    mLoadView.showLoadPage(msg);
                }
                break;
            case LOADSUCES://加载成功
                if (dataList == null || dataList.size() == 0) {
                    mLoadView.showSuccess();
                }
                if (mListView != null) {
                    mListView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mListView.onRefreshComplete();
                            //更改 底部导航栏
                            if (mOnRefreshingListener != null) {
                                mOnRefreshingListener.onDataRefreshingEnd();
                            }

                        }
                    }, 800);
                }
                break;
            case DATAEMPTY://空数据
                if (dataList == null || dataList.size() == 0) {
                    mLoadView.showEmptyPage(LoadViewConfig.EMPTY_DEFAULT, "暂时没有帖子");
                }
                if (mListView != null) {

                    mListView.onRefreshComplete();

                }

                break;
        }
        if (msg != null && !"".equals(msg)) {
            notify_view_text.setText(msg);
            notify_view_text.setVisibility(View.VISIBLE);
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    notify_view_text.setVisibility(View.GONE);
                }
            }, 2000);
        }
    }


    private View headView;//头部轮播图
    private LinearLayout contentLayout;//主题父控件

    /**
     * 添加头部数据
     *
     * @param topicInfos
     */
    private void initHeadData(List<TopicInfo> topicInfos) {
//        if (topicInfos == null || topicInfos.size() == 0 || mListView == null) {
//            return;
//        }
//        if (headView == null) {
        headView = activity.getLayoutInflater().inflate(R.layout.layout_topic_recommend_head, null);
//            contentLayout = (LinearLayout) headView.findViewById(R.id.mRadioGroup_content);
//            HorizontalScrollView scrollView = (HorizontalScrollView) headView.findViewById(R.id.mColumnHorizontalScrollView);
//            scrollView.setParam(activity, ViewSizeUtils.getWidthPixels(), 3, contentLayout);
//            mListView.getRefreshableView().addHeaderView(headView);
//        }
//        contentLayout.removeAllViews();//移除所有的主题
//        View.OnClickListener onClickListener = new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                TopicInfo topicInfo = (TopicInfo) v.getTag();
//                Intent intent = new Intent(activity, TopicDetailActivity.class);
//                intent.putExtra(BaseActivity.PARAMETER1, topicInfo.getTopicId());
//                activity.startActivity(intent);
//            }
//        };
//        for (int i = 0; i < topicInfos.size(); i++) {
//            TopicInfo topicInfo = topicInfos.get(i);
//            if (topicInfo != null) {
//                TopicView view = new TopicView(activity);
//                view.setData(topicInfo);
//                view.setOnClickListener(onClickListener);
//                contentLayout.addView(view);
//            }
//        }
    }


    /**
     * 数据去重
     *
     * @param list
     */
    private void dataRevisited(List<PostItemBean> list) {
        if (list == null || list.size() == 0) {
            return;
        }
        for (int i = 0; i < list.size(); i++) {
            if (i >= list.size()) {
                break;
            }
            PostItemBean postItemBean = list.get(i);
            if (postItemBean == null) {
                continue;
            }
            //开始去重计算
            if (listHasp.get(postItemBean.getICommentId()) == null) {
                listHasp.put(postItemBean.getICommentId(), postItemBean.getICommentId());
            } else {
                list.remove(i);//如果包含则替换
                i--;

            }
        }
    }


    /**
     * 重写下拉刷新
     *
     * @param refreshView
     */
    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        if (this.isinit) {
            this.mMark = 0;
        } else {
            this.mMark = 1;
        }
        super.onPullDownToRefresh(refreshView);
        StatService.onEvent(activity, "042", "精品帖子列表下拉", 1);//统计事件的点击次数
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        this.mMark = 0;
        super.onPullUpToRefresh(refreshView);
        StatService.onEvent(activity, "042", "精品帖子列表上拉", 1);//统计事件的点击次数
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //因为有头部
        if (mListView.getRefreshableView().getHeaderViewsCount() > 0) {
            position = position - mListView.getRefreshableView().getHeaderViewsCount();
        }
        //防止越界
        if (position >= dataList.size()) {
            position = dataList.size() - 1;
        } else if (position < 0) {
            position = 0;
        }
        PostItemBean postItemBean = dataList.get(position);
        if (TextUtils.equals(postItemBean.getCtype(), TypeConstant.FLUSH)) {
            flushData();
        }
    }


    @Override
    public void startActivity(Intent intent) {
        if (activity != null) {
            activity.startActivity(intent);
        } else {
            super.startActivity(intent);
        }
    }

    /**
     * 更新数据适配器
     */
    public void updateAdapter(int zanNum, int commentNum, boolean isDelete) {
        if (mAdapter != null) {
            ((PostItemAdapter) mAdapter).notifyZanComment(zanNum, commentNum, isDelete);
        }
    }

    /**
     * 返回当前页面的list集合
     *
     * @return
     */
    public List getDataList() {
        return this.dataList;
    }

    /**
     * 自定义的刷新数据
     *
     * @param isinit
     */
    public void flushData(boolean isinit) {
        this.isinit = isinit;
        listHasp.clear();
        mMark = 0;
        super.flushData();
    }

    public interface OnRefreshingListener {
        void onDataRefreshingStart();

        void onDataRefreshingEnd();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        lastGetTime = "";
    }


    /**
     * 根据 时间间隔 刷新
     */
    public void flushWithTime() {
        Message msg = Message.obtain();
        msg.what = 1;
        handler.sendMessageDelayed(msg, 300);

    }
}
